﻿using Nop.Core.Infrastructure;
using Nop.Core.Plugins;
using Nop.Plugin.Misc.DynamicsCrm.Services;
using Nop.Services.Tasks;
using Nop.Services.Logging;

namespace Nop.Plugin.Misc.DynamicsCrm
{
    public class DynamicsCrmSynchronizationTask : ITask
    {
        /// <summary>
        /// Execute task
        /// </summary>
        public void Execute()
        {
            var pluginFinder = EngineContext.Current.Resolve<IPluginFinder>();
            var logger = EngineContext.Current.Resolve<ILogger>();

            //is plugin installed?
            var pluginDescriptor = pluginFinder.GetPluginDescriptorBySystemName("Misc.DynamicsCrm");
            if (pluginDescriptor == null || !pluginDescriptor.Installed)
                return;

            //is plugin configured?
            var plugin = pluginDescriptor.Instance() as DynamicsCrmPlugin;
            if (plugin == null || !plugin.IsConfigured())
                return;

            var dynamicsCrmApiService = EngineContext.Current.Resolve<IDynamicsCrmApiService>();
            var result = dynamicsCrmApiService.Synchronize();

            logger.InsertLog(Core.Domain.Logging.LogLevel.Information, "Dynamics Crm synchronization task", result.ToHtml());

        }
    }
}